package com.mathlearning.auth.service;

import com.mathlearning.auth.dto.discussion.DiscussionResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 讨论帖子缓存服务
 */
@Service
public class DiscussionCacheService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussionCacheService.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 缓存key前缀
    private static final String DISCUSSION_CACHE_PREFIX = "discussion:detail:";
    private static final String DISCUSSION_LIST_CACHE_PREFIX = "discussion:list:";
    private static final String HOT_TAGS_CACHE_KEY = "discussion:tags:hot";

    // 缓存过期时间
    private static final long DISCUSSION_DETAIL_EXPIRE = 30; // 30分钟
    private static final long DISCUSSION_LIST_EXPIRE = 5;    // 5分钟
    private static final long HOT_TAGS_EXPIRE = 60;          // 60分钟

    /**
     * 缓存讨论详情
     */
    public void cacheDiscussion(Long discussionId, DiscussionResponse discussion) {
        try {
            String key = DISCUSSION_CACHE_PREFIX + discussionId;
            redisTemplate.opsForValue().set(key, discussion, DISCUSSION_DETAIL_EXPIRE, TimeUnit.MINUTES);
            logger.info("缓存讨论详情成功: discussionId={}", discussionId);
        } catch (Exception e) {
            logger.error("缓存讨论详情失败: discussionId={}", discussionId, e);
        }
    }

    /**
     * 获取缓存的讨论详情
     */
    public DiscussionResponse getCachedDiscussion(Long discussionId) {
        try {
            String key = DISCUSSION_CACHE_PREFIX + discussionId;
            Object cached = redisTemplate.opsForValue().get(key);
            if (cached != null) {
                logger.info("从缓存获取讨论详情: discussionId={}", discussionId);
                return (DiscussionResponse) cached;
            }
        } catch (Exception e) {
            logger.error("从缓存获取讨论详情失败: discussionId={}", discussionId, e);
        }
        return null;
    }

    /**
     * 删除讨论缓存
     */
    public void deleteDiscussionCache(Long discussionId) {
        try {
            String key = DISCUSSION_CACHE_PREFIX + discussionId;
            redisTemplate.delete(key);
            logger.info("删除讨论缓存成功: discussionId={}", discussionId);
        } catch (Exception e) {
            logger.error("删除讨论缓存失败: discussionId={}", discussionId, e);
        }
    }

    /**
     * 缓存讨论列表
     */
    public void cacheDiscussionList(String cacheKey, Object listData) {
        try {
            String key = DISCUSSION_LIST_CACHE_PREFIX + cacheKey;
            redisTemplate.opsForValue().set(key, listData, DISCUSSION_LIST_EXPIRE, TimeUnit.MINUTES);
            logger.info("缓存讨论列表成功: cacheKey={}", cacheKey);
        } catch (Exception e) {
            logger.error("缓存讨论列表失败: cacheKey={}", cacheKey, e);
        }
    }

    /**
     * 获取缓存的讨论列表
     */
    public Object getCachedDiscussionList(String cacheKey) {
        try {
            String key = DISCUSSION_LIST_CACHE_PREFIX + cacheKey;
            Object cached = redisTemplate.opsForValue().get(key);
            if (cached != null) {
                logger.info("从缓存获取讨论列表: cacheKey={}", cacheKey);
                return cached;
            }
        } catch (Exception e) {
            logger.error("从缓存获取讨论列表失败: cacheKey={}", cacheKey, e);
        }
        return null;
    }

    /**
     * 清除所有讨论列表缓存
     */
    public void clearDiscussionListCache() {
        try {
            // 删除所有列表缓存
            var keys = redisTemplate.keys(DISCUSSION_LIST_CACHE_PREFIX + "*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                logger.info("清除所有讨论列表缓存成功，共{}条", keys.size());
            }
        } catch (Exception e) {
            logger.error("清除讨论列表缓存失败", e);
        }
    }

    /**
     * 缓存热门标签
     */
    public void cacheHotTags(Object tags) {
        try {
            redisTemplate.opsForValue().set(HOT_TAGS_CACHE_KEY, tags, HOT_TAGS_EXPIRE, TimeUnit.MINUTES);
            logger.info("缓存热门标签成功");
        } catch (Exception e) {
            logger.error("缓存热门标签失败", e);
        }
    }

    /**
     * 获取缓存的热门标签
     */
    public Object getCachedHotTags() {
        try {
            Object cached = redisTemplate.opsForValue().get(HOT_TAGS_CACHE_KEY);
            if (cached != null) {
                logger.info("从缓存获取热门标签");
                return cached;
            }
        } catch (Exception e) {
            logger.error("从缓存获取热门标签失败", e);
        }
        return null;
    }

    /**
     * 更新讨论缓存中的点赞数
     */
    public void updateDiscussionLikes(Long discussionId, Integer likes, Boolean isLiked) {
        try {
            DiscussionResponse cached = getCachedDiscussion(discussionId);
            if (cached != null) {
                cached.setLikes(likes);
                cached.setIsLiked(isLiked);
                cacheDiscussion(discussionId, cached);
                logger.info("更新讨论缓存点赞数: discussionId={}, likes={}", discussionId, likes);
            }
        } catch (Exception e) {
            logger.error("更新讨论缓存点赞数失败: discussionId={}", discussionId, e);
        }
    }

    /**
     * 更新讨论缓存中的收藏数
     */
    public void updateDiscussionFavorites(Long discussionId, Integer favorites, Boolean isFavorited) {
        try {
            DiscussionResponse cached = getCachedDiscussion(discussionId);
            if (cached != null) {
                cached.setFavorites(favorites);
                cached.setIsFavorited(isFavorited);
                cacheDiscussion(discussionId, cached);
                logger.info("更新讨论缓存收藏数: discussionId={}, favorites={}", discussionId, favorites);
            }
        } catch (Exception e) {
            logger.error("更新讨论缓存收藏数失败: discussionId={}", discussionId, e);
        }
    }

    /**
     * 更新讨论缓存中的评论数
     */
    public void updateDiscussionComments(Long discussionId, Integer comments) {
        try {
            DiscussionResponse cached = getCachedDiscussion(discussionId);
            if (cached != null) {
                cached.setComments(comments);
                cacheDiscussion(discussionId, cached);
                logger.info("更新讨论缓存评论数: discussionId={}, comments={}", discussionId, comments);
            }
        } catch (Exception e) {
            logger.error("更新讨论缓存评论数失败: discussionId={}", discussionId, e);
        }
    }
}








